﻿using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using suirui.ZhuMu.Common;
using suirui.ZhuMu.Entity.Entities;
using suirui.ZhuMu.Log;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace suirui.ZhuMu.Framework
{
    public static class TokenOperate
    {
        private readonly static string signingKey = AppConfigration.Configuration["SecurityKey"];
        /// <summary>
        /// 生成访问令牌
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        public static string GenerateAccessToken(Claim[] claims)
        {
            /**
             *  Claims (Payload)
                Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段，下面节选一些字段:

                iss: The issuer of the token，token 是给谁的
                sub: The subject of the token，token 主题
                exp: Expiration Time。 token 过期时间，Unix 时间戳格式
                iat: Issued At。 token 创建时间， Unix 时间戳格式
                jti: JWT ID。针对当前 token 的唯一标识
                除了规定的字段外，可以包含其他任何 JSON 兼容的字段。
             * */

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey));
            string expiredTime = AppConfigration.Configuration["expiredTime"];
            int time = string.IsNullOrWhiteSpace(expiredTime) ? 30 : Convert.ToInt32(expiredTime);

            var token = new JwtSecurityToken(
                issuer: AppConfigration.Configuration["Issuer"],
                audience: AppConfigration.Configuration["Audience"],
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(time),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        /// <summary>
        /// 生成刷新Token
        /// </summary>
        /// <returns></returns>
        public static string GenerateRefreshToken()
        {
            var randomNumber = new byte[32];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomNumber);
                return Convert.ToBase64String(randomNumber);
            }
        }

        /// <summary>
        /// 从Token中获取用户身份
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static ClaimsPrincipal GetPrincipalFromAccessToken(string token)
        {
            var handler = new JwtSecurityTokenHandler();

            try
            {
                return handler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey)),
                    ValidateLifetime = false,
                    //注意这是缓冲过期时间，总的有效时间等于这个时间加上jwt的过期时间，如果不配置，默认是5分钟
                    ClockSkew = TimeSpan.FromSeconds(1),
                }, out SecurityToken validatedToken);
            }
            catch (Exception ex)
            {
                DefaultLogFactory.Instance.Exception_Loger.Error(ex.ToString());
                return null;
            }
        }

        public static Claim[] GetClaims(User user)
        {
            return new[]
                {
                new Claim(JwtClaimTypes.Audience,AppConfigration.Configuration["Audience"]),
                new Claim(JwtClaimTypes.Issuer,AppConfigration.Configuration["Issuer"]),
                new Claim(JwtClaimTypes.Name, user.NickName),
                new Claim(JwtClaimTypes.Role, user.Role.ToString()),
                new Claim(JwtClaimTypes.Id, user.UserId.ToString()),
            };
        }
    }
}
